/**
 * Created by chocolate on 16/5/27.
 */

import React, {
  Component,
  StyleSheet,
  Text,
  TextInput,
  View,
  TabBarIOS,
  ListView,
  TouchableOpacity,
  Image,
} from 'react-native';

var Title = require('./Title');

var query = require('./Query').query;
//var query = new Query();
import Calendar from 'react-native-calendar';
import SegmentedView from 'react-native-segmented-view';

var statusStrArray = ['过早入校','正常入校','迟到','早退','正常离校','过晚离校','未按时入校','未按时离校'];
class DiCalendar extends Component{
  constructor(props){
    super(props);
    this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.childList = this.props.childList;
    this.eventList = [];                                //从服务器获取的event列表
    this.state = {
      childNames:this._getChildNameArray(this.childList),       //作为segment的数据源
      selectedIndex:0,                                //SegmentedControlIOS的默认选项页
      selectedDate:new Date(),
      parent:this.props.user,                         //当前家长对象(从login模块传递过来的)
      dataSource:this.ds.cloneWithRows([])  //ListView的数据源
    }
  }

  /**
   * 根据家长电话号码到服务器查找其关联的所有学生,
   * 用户名称(电话)是由login模块传递过来
   */
  componentDidMount(){
   this._refreshEvnetList(this.state.selectedDate);
  }

  /**
     * 处理事件列表，分析出状态编码，状态字符串，以及告警，
     * 并将这些信息插入到事件列表中，用于后续的界面渲染
     */
    _processEventList(){
        if(this.eventList.length === 0){
            return;
        }
        this.eventList.forEach((item, index, array)=>{
              var code=this._parseSchoolStatus(item.type,item.time);
              item.status_code = code;
              item.status_str = statusStrArray[code];
              item.alarm = (code != 1 && code != 4)?true:false;
        })
    }

    /**
     * 根据出入类型和出入事件分析抱抱事件
     * 返回学生状态编码(入校和出现门限时间从服务器中获取)
     */
    _parseSchoolStatus(eventType,eventTime){

        enterDate = new Date();
        //测试代码
        enterDate.setFullYear(2016);
        enterDate.setMonth(6-1);
        enterDate.setDate(6);

        enterDate.setHours(9);
        enterDate.setMinutes(0);
        enterDate.setSeconds(0);

        enterThreshDate = new Date();
         //测试代码
        enterThreshDate.setFullYear(2016);
        enterThreshDate.setMonth(6-1);
        enterThreshDate.setDate(6);
        enterThreshDate.setHours(9-1);
        enterThreshDate.setMinutes(0);
        enterThreshDate.setSeconds(0);

        leaveDate = new Date();
        //测试代码
        leaveDate.setFullYear(2016);
        leaveDate.setMonth(6-1);
        leaveDate.setDate(6);
        leaveDate.setHours(18);
        leaveDate.setMinutes(0);
        leaveDate.setSeconds(0);

        leaveThreshDate = new Date();
        //测试代码
        leaveThreshDate.setFullYear(2016);
        leaveThreshDate.setMonth(6-1);
        leaveThreshDate.setDate(6);
        leaveThreshDate.setHours(18+1);
        leaveThreshDate.setMinutes(0);
        leaveThreshDate.setSeconds(0);

        // var year = Number(eventTime.substring(0,4));
        // var month = Number(eventTime.substring(5,7))-1;
        // var day = Number(eventTime.substring(8,10));
        // var hour = Number(eventTime.substring(11,13));
        // var minute = Number(eventTime.substring(14,16));
        // var second = Number(eventTime.substring(17,19));
        // eventDate = new Date(year,month,day,hour,minute,second);
        eventDate = Date.FromString(eventTime);

        var code ;
        if(eventType === 0)
        {
            if(eventDate < enterThreshDate)
            {
                code = 0;   //过早入校
            }
            else if(eventDate > enterThreshDate && eventDate < enterDate)
            {
                code = 1; // 按时入校
            }
            else if(eventDate > enterDate)
            {
                code = 2;  //迟到入校
            }
        }
        else if(eventType === 1)
        {
            if(eventDate < leaveDate)
            {
                code = 3;   //早退离校
            }
            else if(eventDate > leaveDate && eventDate < leaveThreshDate)
            {
                code = 4;   //正常离校
            }
            else if(eventDate > leaveThreshDate)
            {
                code = 5;   //过晚离校
            }
        }
        else if(eventType === 2)
        {
            code = 6;  //未按时入校
        }
        else if(eventType === 3)
        {
            code = 7;  //未按时离校
        }
        return code;
    }

  /**
   * 根据上层模块传入的孩子列表，获取孩子姓名字符串数组，
   *  主要是为了用来更新segment
   */
  _getChildNameArray(childList){
    var childNameList = [];
    childList.forEach((item, index, array) =>{
      childNameList.push(item.name);
    })
    return childNameList;
  }

  _refreshEvnetList(date){
    this.eventList = [];
    console.log("查询学生"+this.childList[this.state.selectedIndex].bbId+"在"+date+"的滴卡记录");
    query.getEventQuery(this.childList[this.state.selectedIndex].bbId,date.Format('yyyy-MM-dd'),this,function(owner,response){
      if(response.success === true){
        owner.eventList = response.message;
        owner._processEventList();
        owner._updateListView();}})
  }

  _updateListView(){
    this.setState({dataSource:this.ds.cloneWithRows(this.eventList)});
  }

  /**
   * 点击返回按钮,返回上层界面
   * @private
   */
  _onPressReturn(){
    this.props.navigator.pop();
  }

  /**
   * 渲染孩子事件列表的每一行数据
   * @param rowData
   * @param sectionID
   * @param rowID
   * @returns {XML}
   */
  renderEventRecord(rowData: string,sectionID: number, rowID: number){
      //在抱抱界面看到的是当天的事件数据,因此不需要日期,只需要时间
      var time = rowData.time.substring(11,19);

      return (
          <View style={styles.row}>
              <View style={styles.timeline}/>
              <Image style={styles.bubblestate} source={(rowData.alarm === true) 
                                      ? require('../../icon/timeline-alarm.png')
                                      : require('../../icon/timeline-check.png')}/> 

              <TouchableOpacity style={{alignItems:'center'}}>
                  <Image style={styles.bubble} source={require('../../icon/bubble.png')}>
                      <Text style={styles.bubbleText}>{time}</Text>
                      <Text style={styles.bubbleText}>{rowData.status_str}</Text>
                  </Image>
              </TouchableOpacity>
          </View>)
  }

  onDateSelect(datestr){
   console.log(typeof (datestr));

    //将字符串转化为date类型(2016-06-06T00:00:00+08:00)
    var year = datestr.substr(0,4);
    var month = datestr.substr(5,2);
    var day = datestr.substr(8,2);
    var date = new Date();
    date.setFullYear(year);
    date.setMonth(month-1);
    date.setDate(day);
    console.log("转换后的日期对象："+date.toString());
    this.setState({selectedDate:date});
    this._refreshEvnetList(date);

  }

   /**
   * 点击SegmentBar更换学生,会触发重新刷新课程表
   */
  _onPressSegment(index){
    this.setState({selectedIndex: index});
    this._refreshEvnetList(this.state.selectedDate);
  }

  render(){

    return(

          <View style={styles.container}>
            <Title title={{center:"滴卡记录",left:"返回",leftAct:this._onPressReturn.bind(this)}}></Title>

            <SegmentedView
                titles={this.state.childNames}
                index={this.state.selectedIndex}
                stretch={true}
                barPosition={'bottom'}
                onPress={this._onPressSegment.bind(this)}
                style={{flex:0}}/>

            <Calendar
              scrollEnabled={true}              // False disables swiping. Default: True
              showControls={true}               // False hides prev/next buttons. Default: False
              titleFormat={'YYYY年MM月'}         // Format for displaying current month. Default: 'MMMM YYYY'
              dayHeadings={['日','一','二','三','四','五','六']}  // Default: ['S', 'M', 'T', 'W', 'T', 'F', 'S']
              prevButtonText={'上一月'}           // Text for previous button. Default: 'Prev'
              nextButtonText={'下一月'}           // Text for next button. Default: 'Next'
              onDateSelect={(date) => this.onDateSelect(date)} // Callback after date selection
              customStyle={{day: {fontSize: 15, textAlign: 'center'},
                    calendarContainer:{backgroundColor:'#FFF'},
                    controlButton:{backgroundColor:'#06a9fe'},
                    controlButtonText:{color:'#FFF'}}} // Customize any pre-defined styles
            />
            <Text style={{marginTop:20,marginLeft:40}}>滴卡记录:</Text>

            <View style = {styles.ItemContainer}>
              <ListView dataSource={this.state.dataSource}
                        renderRow={this.renderEventRecord}
                        enableEmptySections={true}
                        style={styles.listView} />
            </View>

          </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#eeeeee',
    flex: 1,
  },
  Title: {
    height: 40,
    marginTop: 20,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    borderColor: 'gray',
    borderTopWidth: 1,
    borderBottomWidth: 1,
  },
  ItemContainer:{
    flexDirection:'column',
    alignItems:'center',
    flex:1
  },
  listView: {
    marginLeft:170,
    marginRight:170,
    paddingTop: 5,

  },
  row:{
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems:'center',

  },
  text:{
    textAlign:'center',
    fontSize:10,
    backgroundColor:'rgba(254,254,254,0)',
  },
  timeline:{
    width:1,
    alignSelf:'stretch',
    borderStyle:'solid',
    borderWidth:1,
    borderColor:'#d4d4d4',
    marginLeft:30,
  }, 
  bubble:{
    flexDirection:'row',
    alignItems:'center',
    justifyContent:'space-between',
    paddingLeft:30,
    paddingRight:30,
    marginTop:25,
    marginLeft:5,
  },
  bubblestate:{
    marginLeft:-10,
    marginTop:20,
  },
  bubbleText:{
    color:'#a7a7a7',
    fontSize:20,
    backgroundColor:'#FFF'
  },

})

module.exports = DiCalendar;